package com.njtoyo.taxi.admin.utils;

import cn.hutool.core.date.DateUtil;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.njtoyo.taxi.admin.config.oss.OOSConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OssClient {

    private static final String REMOTE_URL = "https://sso.ctyun.cn";

    private static final String OOS_URL = "https://oos-cn.ctyunapi.cn/";

    public static final String OOS_BUCKET_NAME_CARAPPADV = "njtoyo-taxi-admin/adv/car_app";
    public static final String OOS_BUCKET_NAME_APP = "njtoyo-taxi-admin/app";
    public static final String OOS_BUCKET_NAME_CALLRECORD = "njtoyo-taxi-admin/callrecord";


    /**
     * 天翼云OSS上传资源
     *
     * @param source
     * @param bucketKey
     * @return
     */
    public String putObject(File source, String bucketKey) {
        AmazonS3 client = OOSConfig.getClientFromConfig();
        PutObjectRequest request = new PutObjectRequest(OOS_BUCKET_NAME_CARAPPADV, bucketKey, source);
        ObjectMetadata metadata = new ObjectMetadata();
        CtyunBucketDataLocation dataLocation = new CtyunBucketDataLocation();
        dataLocation.setType(CtyunBucketDataLocation.CtyunBucketDataType.Specified);
        List<String> dataRegions = new ArrayList<>();
        dataRegions.add("QingDao");
        dataLocation.setDataRegions(dataRegions);
        metadata.setDataLocation(dataLocation);
        request.setMetadata(metadata);
        client.putObject(request);
        return OOS_URL + OOS_BUCKET_NAME_CARAPPADV + "/" + bucketKey;
    }


    /**
     * 简单上传-流式上传-公共读
     *
     * @param bucketName  bucket名称
     * @param key         文件名
     * @param inputStream 输入流
     * @return PutObjectResult 上传结果
     */
//    public static PutObjectResult putObjectByInputStream(String bucketName, String key, InputStream inputStream) {
//        ObjectMetadata metadata = new ObjectMetadata();
//        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
//        // 准备OSS上传对象请求
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);
//        putObjectRequest.setMetadata(metadata);
//        //设置上传对象的Acl为公共读，私有写
//        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
//        // 上传
//        return tianyiyunOssClient.putObject(putObjectRequest);
//    }

    /**
     * 
     * @param inputStream
     * @param fileName 文件名
     * @param bucket 桶名
     * @return
     */
    public static String uploadFile(InputStream inputStream, String fileName,String bucket) {
        try {
            AmazonS3 client = OOSConfig.getClientFromConfig();
            String remoteFilePath = DateUtil.formatDate(DateUtil.date());
            String dir = remoteFilePath + "/"; // 用户上传文件时指定的前缀。
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String bucketKey = IdWorker.getIdStr();
            String path = dir + bucketKey + suffix;
            try {
                objectMetadata.setContentLength(inputStream.available());
                // 上传文件
                log.info("开始上传文件到oss");
                log.info("bucket: " + bucket);
                log.info("path: " + path);
                log.info("inputStream: " + inputStream);
                log.info("objectMetadata: " + objectMetadata);
                client.putObject(bucket, path, inputStream, objectMetadata);

                //获取文件预览地址
                return OOS_URL + bucket + "/" + path;
            } catch (Exception e) {
                log.error("上传文件到oos失败", e);
            } finally {
                if (client != null) {
                    ((AmazonS3Client) client).shutdown();
                }
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static String getObjectUrl(String bucketName, String key) {
        AmazonS3 client = OOSConfig.getClientFromConfig();
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key)
                .withMethod(HttpMethod.GET);
        return client.generatePresignedUrl(request).toString();
    }


    public static void main(String[] args) {
        OssClient client = new OssClient();
        client.putObject(new File("/Users/saber/Pictures/c52b1bf5c924d2ed808805ebf2d1feb3.jpg"), "test.jpg");
    }

}
